/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fourbox.client;

import fourbox.Metafile;
import fourbox.server.Server;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hartono
 */
public class ClientDownloader implements Runnable{

    List queue ;
    String workingPath;
    
    public static void main (String args[]) throws IOException{
        String workingPath = "D:/Fourbox/";
        List queue= Collections.synchronizedList(new ArrayList());
        Metafile b = Metafile.createMetafile("Repository/tono",new File("Repository/tono/b.txt"));
        b.isFile=true;
        b.lastModified = 1336014429171l;
        queue.add(b);
        
        ClientDownloader downloader = new ClientDownloader(queue, workingPath);
//        downloader.start();
    }
    
    public ClientDownloader(List queue, String workingPath) {
        this.queue = queue;        
        this.workingPath = workingPath;
    }
        

    @Override
    public void run() {
    // initialize socket for listening        
        System.out.println("Client Downloader : Starting ...");
        ServerSocket serverSocket = null;
        boolean listening = true;        
        try {
            serverSocket = new ServerSocket(Client.CLIENT_DOWNLOAD_PORT);
            System.out.println("Client Downloader : Start Listening ...");
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Client Downloader : Cannot listen on port "+Client.CLIENT_DOWNLOAD_PORT);
//            System.exit(-1);
        }        
        
        // start listening
        while(listening){
            try {
                new Thread(new ClientDownloadHandler( serverSocket.accept(), queue,workingPath)).start();
            } catch (IOException ex) {
                Logger.getLogger(ClientDownloader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }        
        try {
            serverSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(ClientDownloader.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Client Downloader : Closing ...");
    }
    
}
